package com.xbongbong.workflow.service.help;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.formula.constant.Constant;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.BusinessUserTeamHelp;
import com.xbongbong.paas.help.FormDataHelp;
import com.xbongbong.paas.help.team.TeamMessageHelper;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.service.WorkflowOperatorDataService;
import com.xbongbong.paas.service.team.TeamDataBusinessHelp;
import com.xbongbong.paas.service.workflow.WorkflowDataService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.domain.entity.LabelEntity;
import com.xbongbong.pro.enums.PackageStatusEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.team.TeamAfterVerifyDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.SupplierContactEnum;
import com.xbongbong.saas.help.SaveFormatHelp;
import com.xbongbong.saas.model.ContactModel;
import com.xbongbong.saas.model.LabelModel;
import com.xbongbong.saas.model.SupplierContactModel;
import com.xbongbong.saas.service.toolbox.help.PackageStatusHelp;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.service.strategy.data.WorkflowDataProcessStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 工作流新建编辑数据处理help
 * @author 魏荣杰
 *
 */
@Slf4j
@Component
public class WorkflowDataHelp {

    @Resource
    @Lazy
    private Map<Integer, WorkflowDataProcessStrategy> workflowDataProcessStrategyMap;
    @Resource
    private PackageStatusHelp packageStatusHelp;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private LabelModel labelModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private WorkflowOperatorDataService workflowOperatorDataService;
    @Resource
    private WorkflowDataService workflowDataService;
    @Resource
    private ContactModel contactModel;
    @Resource
    private SupplierContactModel supplierContactModel;
    @Resource
    private TeamDataBusinessHelp teamDataBusinessHelp;
    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private TeamMessageHelper teamMessageHelper;
    @Resource
    private BusinessUserTeamHelp businessUserTeamHelp;
    @Resource
    private FormDataHelp formDataHelp;



    /**
     * Description: 处理新建操作整个工作流结束后的操作
     * @param
     * @param workflowTransferPOJO
     * @param saasNeedRedundantAttrPojo
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2021/7/12 11:27
     * @since
     */
    public void processForSave(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        Data pojoData = workflowTransferPOJO.getData();
        Integer saasMark = pojoData.getSaasMark();
        if (Objects.equals(saasMark, SaasMarkEnum.SAAS.getCode())) {
            // saas
            Integer businessType = pojoData.getBusinessType();
            WorkflowDataProcessStrategy workflowDataProcessStrategy = workflowDataProcessStrategyMap.get(businessType);
            workflowDataProcessStrategy.save(workflowTransferPOJO, saasNeedRedundantAttrPojo);
        } else if (Objects.equals(saasMark, SaasMarkEnum.PAAS.getCode())) {
            // paas
            WorkflowDataProcessStrategy workflowDataProcessStrategy = workflowDataProcessStrategyMap.get(XbbRefTypeEnum.PAAS.getCode());
            workflowDataProcessStrategy.save(workflowTransferPOJO, saasNeedRedundantAttrPojo);
        }

        if (Objects.nonNull(saasNeedRedundantAttrPojo)) {
            TeamAfterVerifyDTO teamAfterVerifyDTO = saasNeedRedundantAttrPojo.getTeamAfterVerifyDTO();
            teamMessagePushForSave(workflowTransferPOJO, teamAfterVerifyDTO);
        }

    }

    /**
     * Description: 团队消息推送
     * @param workflowTransferPOJO
	 * @param teamAfterVerifyDTO
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2022/11/1 10:56
     * @since
     */
    private void teamMessagePushForSave(WorkflowTransferPOJO workflowTransferPOJO, TeamAfterVerifyDTO teamAfterVerifyDTO) {
        Data pojoData = workflowTransferPOJO.getData();
        if (Objects.nonNull(teamAfterVerifyDTO)) {
            String corpid = teamAfterVerifyDTO.getCorpid();
            Integer businessType = pojoData.getBusinessType();
            Long dataId = pojoData.getId();
            Integer saasMark = pojoData.getSaasMark();
            if (Objects.equals(saasMark, SaasMarkEnum.SAAS.getCode())) {
                PaasFormDataEntity paasFormDataEntity = formDataHelp.getFormData(dataId, corpid, pojoData.getBusinessType());
                if (Objects.isNull(paasFormDataEntity)) {
                    return;
                }
                List<UserTeamEntity> userTeamList = businessUserTeamHelp.getUserTeamList(Arrays.asList(dataId), corpid, businessType, false);

                Set<String> newMainList = userTeamList.stream().filter(v -> Objects.equals(v.getIsMain(), Constant.ONE)).map(UserTeamEntity::getUserId).collect(Collectors.toSet());
                Set<String> newCoList = userTeamList.stream().filter(v -> Objects.equals(v.getIsMain(), Constant.ZERO)).map(UserTeamEntity::getUserId).collect(Collectors.toSet());

                try {
                    teamMessageHelper.addUserPush(teamAfterVerifyDTO, true, null, newMainList, paasFormDataEntity);
                    teamMessageHelper.addUserPush(teamAfterVerifyDTO, false, null, newCoList, paasFormDataEntity);
                } catch (Exception e) {
                    log.error("WorkflowDataHelp.teamMessagePushForSave add team message fail", e);
                }
            }

        }
    }


    /**
     * Description: 处理编辑操作整个工作流结束后的操作
     * @param workflowTransferPOJO
	 * @param saasNeedRedundantAttrPojo
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2021/7/12 14:20
     * @since
     */
    public void processForUpdate(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        Data pojoData = workflowTransferPOJO.getData();
        Integer saasMark = pojoData.getSaasMark();
        if (Objects.equals(saasMark, SaasMarkEnum.SAAS.getCode())) {
            // saas
            Integer businessType = pojoData.getBusinessType();
            WorkflowDataProcessStrategy workflowDataProcessStrategy = workflowDataProcessStrategyMap.get(businessType);
            workflowDataProcessStrategy.update(workflowTransferPOJO, saasNeedRedundantAttrPojo);
        } else if (Objects.equals(saasMark, SaasMarkEnum.PAAS.getCode())) {
            // paas
            WorkflowDataProcessStrategy workflowDataProcessStrategy = workflowDataProcessStrategyMap.get(XbbRefTypeEnum.PAAS.getCode());
            workflowDataProcessStrategy.update(workflowTransferPOJO, saasNeedRedundantAttrPojo);
        }
        //校验团队数据，工作流结束跟备份数据比较，有团队变动才需要走继承规则
        if (Objects.nonNull(saasNeedRedundantAttrPojo)) {
            TeamAfterVerifyDTO teamAfterVerifyDTO = saasNeedRedundantAttrPojo.getTeamAfterVerifyDTO();
            if(Objects.nonNull(teamAfterVerifyDTO)){
                PaasFormDataEntityExt formData = formDataHelp.getFormData(pojoData.getId(), workflowTransferPOJO.getCorpid(), pojoData.getBusinessType());

                boolean updateTeamFlag = compareTeam(teamAfterVerifyDTO, workflowTransferPOJO.getBackupDataId(), formData);
                if(updateTeamFlag){
                    teamDataBusinessHelp.inheritanceSaveWithoutThread(saasNeedRedundantAttrPojo.getTeamAfterVerifyDTO());
                }
            }
        }

    }

    public void batchEditContact(SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo, UserVO loginUser, String creatorId, String corpid, Long dataId, String name, Integer isImport, String attr, XbbRefTypeEnum xbbRefTypeEnum) throws XbbException{

        List<ValidateDataDTO> needAddValidateDataDTO = null;
        if (saasNeedRedundantAttrPoJo != null) {
            needAddValidateDataDTO = saasNeedRedundantAttrPoJo.getNeedAddValidateDataDTO();
            for (ValidateDataDTO validateDataDTO : needAddValidateDataDTO) {
                validateDataDTO.setProcessCreatorId(creatorId);
            }
        }
        if (!Objects.isNull(needAddValidateDataDTO)) {
            if (Objects.nonNull(needAddValidateDataDTO) && !needAddValidateDataDTO.isEmpty() && !Objects.equals(needAddValidateDataDTO.get(0).getIsImport(), BasicConstant.ONE)) {
                //非导入时判断数据量限制
                Integer oneStatus = packageStatusHelp.getPackageStatus(corpid, ValueAddedTypeEnum.ONE_FORM_DATA_NUM, needAddValidateDataDTO.size(), xbbRefTypeEnum, needAddValidateDataDTO.get(0).getFormId());
                Integer allStatus = packageStatusHelp.getPackageStatus(corpid, ValueAddedTypeEnum.TOTAL_FORM_DATA_NUM, needAddValidateDataDTO.size());
                if ( !Objects.equals(oneStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(oneStatus, PackageStatusEnum.WARNING.getCode()) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.SINGLE_TABLE_NUM_LIMIT);
                }

                if ( !Objects.equals(allStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(allStatus, PackageStatusEnum.WARNING.getCode()) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.TOTAL_TABLE_NUM_LIMIT);
                }
            }
            String labelAttr = null;
            Map<String, Long> labelPojoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(needAddValidateDataDTO) && !needAddValidateDataDTO.isEmpty() && Objects.equals(needAddValidateDataDTO.get(0).getIsImport(), BasicConstant.ONE)) {
                PaasFormExplainEntity contactExplain = paasFormExplainModel.getByBusinessType(xbbRefTypeEnum.getCode(), needAddValidateDataDTO.get(0).getCorpid());
                List<FieldAttrEntity> explainList = JSONArray.parseArray(contactExplain.getExplains(), FieldAttrEntity.class);
                for (FieldAttrEntity item : explainList) {
                    if (Objects.equals(item.getFieldType(), FieldTypeEnum.LABEL.getType())) {
                        labelAttr = item.getAttr();
                    }
                }

                if (StringUtil.isNotEmpty(labelAttr)) {
                    Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    param.put("formId", contactExplain.getFormId());
                    param.put("corpid", contactExplain.getCorpid());
                    param.put("appId", contactExplain.getAppId());
                    param.put("del", DelEnum.NORMAL.getDel());
                    List<LabelEntity> entitys = labelModel.findEntitys(param);
                    entitys.forEach(item -> {
                        labelPojoMap.put(item.getName(), item.getId());
                    });
                }
            }


            for ( ValidateDataDTO validateDataDTO : needAddValidateDataDTO ) {
                if (Objects.isNull(validateDataDTO.getSerialNo())){
                    validateDataDTO.setSerialNo("");
                }
                JSONObject data = validateDataDTO.getData();
                if ( data.isEmpty() ) {
                    continue;
                }

                if (StringUtil.isNotEmpty(labelAttr)){
                    JSONArray jsonArray = new JSONArray();
                    if (data.get(labelAttr) instanceof  String){
                        if (Objects.nonNull(data.get(labelAttr))){
                            String[] split = data.getString(labelAttr).split(",");
                            for (String s : split) {
                                if (Objects.nonNull(labelPojoMap.get(s))) {
                                    jsonArray.add(labelPojoMap.get(s));
                                }
                            }
                        }
                        data.put(labelAttr, jsonArray);
                    }
                }
                // 把关联客户id塞进去
                data.put(attr, dataId);
                if (Objects.equals(XbbRefTypeEnum.CONTACT.getCode(), xbbRefTypeEnum.getCode())) {
                    data.put(ContactEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), name);
                } else if (Objects.equals(XbbRefTypeEnum.SUPPLIER_CONTACT.getCode(), xbbRefTypeEnum.getCode())) {
                    data.put(SupplierContactEnum.SUPPLIER_ID_LINK_TEXT.getAttr(), name);
                }
                SaveFormatHelp.dealLabelData(validateDataDTO.getData(), validateDataDTO.getExplainMap());
                FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
                BeanUtil.copyProperties(validateDataDTO, formDataAddDTO);
                formDataAddDTO.setLoginUser(loginUser);
                formDataAddDTO.setDataList(data);
                PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formDataAddDTO.getFormId(), formDataAddDTO.getCorpid());
                if ( paasFormEntityExt == null ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                }
                PaasFormExplainEntity explainEntity = paasFormExplainModel.getByFormId(validateDataDTO.getFormId(), validateDataDTO.getCorpid());
                Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explainEntity.getExplains(), null);
                // 流水号开启严控模式
                FieldAttrEntity fieldAttrEntity = explainMap.get(FieldTypeEnum.SERIALNO.getAlias());
                if (Objects.nonNull(fieldAttrEntity) && Objects.equals(fieldAttrEntity.getStrictController(), BasicConstant.ONE)) {
                    FormDataAddDTO formDataSaveDTO = new FormDataAddDTO();
                    BeanUtil.copyProperties(validateDataDTO, formDataSaveDTO);
                    formDataSaveDTO.setFormId(formDataAddDTO.getFormId());
                    formDataAddDTO.getDataList().put(FieldTypeEnum.SERIALNO.getAlias(),formDataSaveDTO.getSerialNo());
                    formDataAddDTO.setSerialNo(formDataSaveDTO.getSerialNo());
                }

                formDataAddDTO.setIsImport(isImport);
                formDataAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                formDataAddDTO.setUserId(loginUser.getUserId());
                formDataAddDTO.setLoginUserName(loginUser.getName());
                formDataAddDTO.setOwnerId(validateDataDTO.getOwnerIds());
                formDataAddDTO.setFromApproval(true);
                // 新建
                workflowOperatorDataService.add(formDataAddDTO);
            }
        }
    }



    public void batchEditContactForUpdate(SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo, UserVO loginUser, String creatorId, String corpid, Long dataId, String name, Integer isImport, String attr, XbbRefTypeEnum xbbRefTypeEnum) throws XbbException {
        if (Objects.nonNull(saasNeedRedundantAttrPoJo)) {
            return;
        }

        List<ValidateDataDTO> needAddValidateDataDTO = saasNeedRedundantAttrPoJo.getNeedAddValidateDataDTO();
        List<ValidateDataDTO> needDelValidateDataDTO = saasNeedRedundantAttrPoJo.getNeedDelValidateDataDTO();
        List<ValidateDataDTO> needUpdateValidateDataDTO = saasNeedRedundantAttrPoJo.getNeedUpdateValidateDataDTO();

        // 更新
        if (CollectionsUtil.isNotEmpty(needUpdateValidateDataDTO)) {
            for ( ValidateDataDTO validateDataDTO : needUpdateValidateDataDTO ) {
                JSONObject data = validateDataDTO.getData();
                if ( data.isEmpty() ) {
                    continue;
                }
                // 把关联客户id塞进去
                data.put(attr, dataId);
                FormDataUpdateDTO formDataUpdateDTO = new FormDataUpdateDTO();
                BeanUtil.copyProperties(validateDataDTO, formDataUpdateDTO);
                formDataUpdateDTO.setDataList(data);
                PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
                BeanUtil.copyProperties(formDataUpdateDTO, paasFormDataEntity);
                paasFormDataEntity.setId(formDataUpdateDTO.getDataId());
                PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formDataUpdateDTO.getFormId(), formDataUpdateDTO.getCorpid());
                if ( paasFormEntityExt == null ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                }
                if ( formDataUpdateDTO.getDataList() != null ) {
                    paasFormDataEntity.setData(formDataUpdateDTO.getDataList());
                }
                paasFormDataEntity.setMenuId(paasFormEntityExt.getMenuId());
                paasFormDataEntity.setCreatorId(formDataUpdateDTO.getUserId());
                if ( Objects.nonNull(formDataUpdateDTO.getOwnerId()) && !formDataUpdateDTO.getOwnerId().isEmpty() ) {
                    paasFormDataEntity.setOwnerId(Objects.toString(formDataUpdateDTO.getOwnerId().get(0).getId(), ""));
                }

                formDataUpdateDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
                workflowDataService.update(formDataUpdateDTO);


//                PaasFormDataEntity oldPaasFormDataEntity = proModelService.getOldPaasFormDataEntity(formDataUpdateDTO);
//                Integer noApprovalRequired = 1;
//                if ( paasFormEntityExt.getIsProcessForm().equals(1) && !Objects.equals(formDataUpdateDTO.getIsImport(), 1) ) {
//                    StartProcessDTO startProcessDTO = new StartProcessDTO();
//                    BeanUtil.copyProperties(formDataUpdateDTO, startProcessDTO);
//                    startProcessDTO.setOwnerId(paasFormDataEntity.getOwnerId());
//                    startProcessDTO.setData(formDataUpdateDTO.getDataList());
//                    startProcessDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
//                    startProcessDTO.setFormDataId(formDataUpdateDTO.getDataId());
//                    startProcessDTO.setCreatorId(formDataUpdateDTO.getUserId());
//                    startProcessDTO.setBusinessType(xbbRefTypeEnum.getCode());
//                    StartProcessVO startProcessVO = processStartHelp.startProcess(startProcessDTO, oldPaasFormDataEntity);
//                    if ( Objects.isNull(startProcessVO) ) {
//                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.START_PROCESS_ERROR);
//                    }
//                    noApprovalRequired = startProcessVO.getNoApprovalRequired();
//                }
//                if(noApprovalRequired.equals(1)){
//                    proModelService.update(formDataUpdateDTO, paasFormDataEntity, oldPaasFormDataEntity, paasFormEntityExt);
//                }else {
//                    PaasProcessDataEntity paasProcessDataEntity = new PaasProcessDataEntity();
//                    paasProcessDataEntity.setCorpid(formDataUpdateDTO.getCorpid());
//                    paasProcessDataEntity.setFormDataId(oldPaasFormDataEntity.getId());
//                    paasProcessDataEntity.setBusinessType(XbbRefTypeEnum.CONTACT.getCode());
//                    paasProcessDataEntity.setSaasMark(formDataUpdateDTO.getSaasMark());
//                    proModelService.updateFormDataStatus(paasProcessDataEntity, FlowStatusEnum.IN_APPROVAL.getType());
//                }
            }
        }

        // 删除
        if (CollectionsUtil.isNotEmpty(needDelValidateDataDTO)) {
            List<Long> delDataId = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for ( ValidateDataDTO needDelDTO : needDelValidateDataDTO ) {
                Long id = needDelDTO.getDataId();
                if ( id != null ) {
                    delDataId.add(id);
                }
            }
            switch (xbbRefTypeEnum) {
                case CONTACT:
                    contactModel.deleteBatch(delDataId, corpid);
                    break;
                case SUPPLIER_CONTACT:
                    supplierContactModel.deleteBatch(delDataId, corpid);
                    break;
                default:
            }
        }

        // 新建
        if (CollectionsUtil.isNotEmpty(needAddValidateDataDTO)) {
            batchEditContact(saasNeedRedundantAttrPoJo, loginUser, creatorId, corpid, dataId, name, isImport, attr, xbbRefTypeEnum);
        }

    }

    private boolean compareTeam(TeamAfterVerifyDTO teamAfterVerifyDTO, Long backupDataId, PaasFormDataEntity paasFormDataEntity){
        Long dataId = teamAfterVerifyDTO.getDataId().get(Constant.ZERO);
        Integer businessType = teamAfterVerifyDTO.getBusinessType();
        String corpid = teamAfterVerifyDTO.getCorpid();
        Integer saasMark = teamAfterVerifyDTO.getSaasMark();

        //获取老团队数据
        WorkflowBackupDataEntity backupDataEntity = workflowBackupDataModel.getByKey(backupDataId, corpid);
        if(Objects.isNull(backupDataEntity)){
            return false;
        }
        JSONArray userTeam = backupDataEntity.getData().getJSONArray("userTeam");
        List<UserTeamEntity> userEntities = new ArrayList<>();
        if (Objects.nonNull(userTeam)) {
            userEntities = JSON.parseArray(JSON.toJSONString(userTeam), UserTeamEntity.class);
        }
        List<String> oldMainList = userEntities.stream().filter(v -> Objects.equals(v.getIsMain(), Constant.ONE)).map(UserTeamEntity::getUserId).collect(Collectors.toList());
        List<String> oldCoList = userEntities.stream().filter(v -> Objects.equals(v.getIsMain(), Constant.ZERO)).map(UserTeamEntity::getUserId).collect(Collectors.toList());
        //获取现有团队数据

        List<UserTeamEntity> userTeamList = businessUserTeamHelp.getUserTeamList(Arrays.asList(dataId), corpid, businessType, false);

        Set<String> newMainList = userTeamList.stream().filter(v -> Objects.equals(v.getIsMain(), Constant.ONE)).map(UserTeamEntity::getUserId).collect(Collectors.toSet());
        Set<String> newCoList = userTeamList.stream().filter(v -> Objects.equals(v.getIsMain(), Constant.ZERO)).map(UserTeamEntity::getUserId).collect(Collectors.toSet());

        //团队数据比对
        //新增负责人
        for (String userId : newMainList) {
            if(!oldMainList.contains(userId)){
                Set<String> addMainUserList = teamAfterVerifyDTO.getAddMainUserMap().get(String.valueOf(dataId));
                if(Objects.isNull(addMainUserList)){
                    Set<String> list = new HashSet<>();
                    list.add(userId);
                    teamAfterVerifyDTO.getAddMainUserMap().put(String.valueOf(dataId), list);
                }else{
                    addMainUserList.add(userId);
                }
            }
        }
        //新增协同人
        for (String userId : newCoList) {
            if(!oldCoList.contains(userId)){
                Set<String> addCoUserMap = teamAfterVerifyDTO.getAddCoUserMap().get(String.valueOf(dataId));
                if(Objects.isNull(addCoUserMap)){
                    Set<String> list = new HashSet<>();
                    list.add(userId);
                    teamAfterVerifyDTO.getAddCoUserMap().put(String.valueOf(dataId), list);
                }else{
                    addCoUserMap.add(userId);
                }
            }
        }
        //删除负责人
        for (String userId : oldMainList) {
            if(!newMainList.contains(userId)){
                Set<String> delMainUserList = teamAfterVerifyDTO.getDelMainUserMap().get(String.valueOf(dataId));
                if(Objects.isNull(delMainUserList)){
                    Set<String> list = new HashSet<>();
                    list.add(userId);
                    teamAfterVerifyDTO.getDelMainUserMap().put(String.valueOf(dataId), list);
                }else{
                    delMainUserList.add(userId);
                }
            }
        }
        //删除协同人
        for (String userId : oldCoList) {
            if(!newCoList.contains(userId)){
                Set<String> delCoUserList = teamAfterVerifyDTO.getDelCoUserMap().get(String.valueOf(dataId));
                if(Objects.isNull(delCoUserList)){
                    Set<String> list = new HashSet<>();
                    list.add(userId);
                    teamAfterVerifyDTO.getDelCoUserMap().put(String.valueOf(dataId), list);
                }else{
                    delCoUserList.add(userId);
                }
            }
        }
        //有团队数据改动，才同步下游团队数据
        if(CollectionUtils.isNotEmpty(teamAfterVerifyDTO.getAddMainUserMap().get(String.valueOf(dataId))) ||
                CollectionUtils.isNotEmpty(teamAfterVerifyDTO.getAddCoUserMap().get(String.valueOf(dataId))) ||
                CollectionUtils.isNotEmpty(teamAfterVerifyDTO.getDelMainUserMap().get(String.valueOf(dataId))) ||
                CollectionUtils.isNotEmpty(teamAfterVerifyDTO.getDelCoUserMap().get(String.valueOf(dataId)))){

            // 团队消息推送
            try {
                if (Objects.equals(saasMark, SaasMarkEnum.SAAS.getCode())) {
                    Set<String> addMainUser = teamAfterVerifyDTO.getAddMainUserMap().get(String.valueOf(dataId));
                    if (CollectionsUtil.isNotEmpty(addMainUser)) {
                        teamMessageHelper.addUserPush(teamAfterVerifyDTO, true, null, addMainUser, paasFormDataEntity);
                    }
                    Set<String> delMainUser = teamAfterVerifyDTO.getDelMainUserMap().get(String.valueOf(dataId));
                    if (CollectionsUtil.isNotEmpty(delMainUser)) {
                        teamMessageHelper.delUserPush(teamAfterVerifyDTO, true, null, delMainUser, paasFormDataEntity);
                    }
                    Set<String> addCoUser = teamAfterVerifyDTO.getAddCoUserMap().get(String.valueOf(dataId));
                    if (CollectionsUtil.isNotEmpty(addCoUser)) {
                        teamMessageHelper.addUserPush(teamAfterVerifyDTO, false, null, addCoUser, paasFormDataEntity);
                    }
                    Set<String> delCoUser = teamAfterVerifyDTO.getDelCoUserMap().get(String.valueOf(dataId));
                    if (CollectionsUtil.isNotEmpty(delCoUser)) {
                        teamMessageHelper.delUserPush(teamAfterVerifyDTO, false, null, delCoUser, paasFormDataEntity);
                    }
                }
            } catch (Exception e) {
                log.error("WorkflowDataHelp.compareTeam update team message fail", e);
            }

            return true;
        }
        return false;

    }

}
